package com.bjb.vr.remote.ws.rabbitmq.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bjb.vr.common.constant.RemoteContants;
import com.bjb.vr.common.dto.ResDevice;
import com.bjb.vr.common.dto.SysUpgradeDevLog;
import com.bjb.vr.common.service.ResDeviceService;
import com.bjb.vr.common.service.SysUpgradeDevLogService;
import com.bjb.vr.common.utils.RedisUtil;
import com.bjb.vr.remote.ws.rabbitmq.constants.MessageActionConstants;
import com.bjb.vr.remote.ws.rabbitmq.entity.RabbitWebSocketMsg;
import com.bjb.vr.remote.ws.rabbitmq.handler.MessageHandler;
import com.bjb.vr.remote.ws.redis.constants.RedisConstants;
import com.bjb.vr.remote.ws.websocket.vo.Message;
import com.bjb.vr.remote.ws.websocket.websocket.WebSocketMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @version 1.0.0
 * @description:
 * @author: caihaibo
 * @createDate: 2022/3/29
 */
@Component
@Slf4j
public class CvrApkUpdateStateMessageHandler implements MessageHandler {

    @Autowired
    SysUpgradeDevLogService sysUpgradeDevLogService;

    @Autowired
    ResDeviceService resDeviceService;

    @Autowired
    RedisUtil redisUtil;

    final String  LOCK_KEY = "res_sys_update_dev_log_upgrade_status";
    @Override
    public void process(RabbitWebSocketMsg rabbitWebSocketMsg) {
        String dbLockKey = RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY + LOCK_KEY+ rabbitWebSocketMsg.getDeviceId();

        JSONObject jsonObject = JSONObject.parseObject(rabbitWebSocketMsg.getMsg());

        Message message = JSONObject.toJavaObject(jsonObject, Message.class);

        if(message.getAction().equals(MessageActionConstants.MESSAGE_ACTION_CVR_APK_UPDATE_STATE)){
            log.info("处理头盔大厅升级失败状态上传信息");
            JSONObject _jsonObject = JSONObject.parseObject(message.getCommand().getParameter());
            int apkUpdateState = _jsonObject.getInteger("apkUpdateState");
            String apkUpdateMsg = _jsonObject.getString("apkUpdateMsg");
            String value = String.valueOf(System.currentTimeMillis());
            if(redisUtil.lock(dbLockKey,value,RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY_EXPIRE_TIME)) {
                //更新最近插入设备的状态为失败状态
                sysUpgradeDevLogService.updateSysUpdateState(message.getCommand().getUdid(),apkUpdateState,apkUpdateMsg);
                //设备更新apk失败
                UpdateWrapper<ResDevice> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("apk_need_upd_state", RemoteContants.APK_UPDATE_STATE_FAIL);
                updateWrapper.eq("udid",message.getCommand().getUdid());
                resDeviceService.update(updateWrapper);

                redisUtil.unlock(dbLockKey, value);
            }
        }
    }
}
